from celery import shared_task
import time
import smtplib
from email.mime.text import MIMEText
import requests
import json
from django.core.exceptions import ObjectDoesNotExist
from .models import (
    EmailConfig, DingTalkConfig, FeishuConfig, PushTask, PushHistory
)

@shared_task(bind=True)
def send_email_notification(self, task_id, recipient_email, subject, message):
    try:
        task = PushTask.objects.get(id=task_id)
        email_config = task.email_config
        
        # 创建邮件内容
        msg = MIMEText(message, 'plain', 'utf-8')
        msg['From'] = email_config.smtp_username
        msg['To'] = recipient_email
        msg['Subject'] = subject
        
        # 发送邮件
        if email_config.use_ssl:
            server = smtplib.SMTP_SSL(email_config.smtp_server, email_config.smtp_port)
        else:
            server = smtplib.SMTP(email_config.smtp_server, email_config.smtp_port)
            
        server.login(email_config.smtp_username, email_config.smtp_password)
        server.sendmail(email_config.smtp_username, [recipient_email], msg.as_string())
        server.quit()
        
        # 记录推送历史
        PushHistory.objects.create(
            task=task,
            status='success',
            result_message=f"邮件已成功发送至 {recipient_email}"
        )
        
        return f"Email sent to {recipient_email}"
        
    except ObjectDoesNotExist:
        return "Task not found"
    except smtplib.SMTPException as e:
        PushHistory.objects.create(
            task=task,
            status='failed',
            result_message=f"邮件发送失败: {str(e)}"
        )
        return f"Email sending failed: {str(e)}"
    except Exception as e:
        PushHistory.objects.create(
            task=task,
            status='failed',
            result_message=f"邮件发送过程中发生错误: {str(e)}"
        )
        return f"Error occurred: {str(e)}"

@shared_task(bind=True)
def send_dingtalk_notification(self, task_id, webhook_url, message):
    try:
        task = PushTask.objects.get(id=task_id)
        
        headers = {'Content-Type': 'application/json'}
        data = {
            "msgtype": "text",
            "text": {
                "content": message
            }
        }
        
        response = requests.post(
            webhook_url,
            headers=headers,
            data=json.dumps(data)
        )
        
        if response.status_code == 200:
            PushHistory.objects.create(
                task=task,
                status='success',
                result_message="钉钉消息发送成功"
            )
            return "DingTalk message sent successfully!"
        else:
            PushHistory.objects.create(
                task=task,
                status='failed',
                result_message=f"钉钉消息发送失败: {response.text}"
            )
            return f"DingTalk message failed: {response.text}"
        
    except ObjectDoesNotExist:
        return "Task not found"
    except Exception as e:
        PushHistory.objects.create(
            task=task,
            status='failed',
            result_message=f"钉钉消息发送过程中发生错误: {str(e)}"
        )
        return f"Error occurred: {str(e)}"

@shared_task
def execute_push_task(task_id):
    """
    执行推送任务的主函数
    """
    try:
        task = PushTask.objects.get(id=task_id)
        
        if task.task_type == 'email' and task.email_config:
            send_email_notification.delay(
                task_id=task.id,
                recipient_email=task.email_config.email_address,
                subject=f"{task.keyword.keyword} 推送",
                message=f"这是关于 {task.keyword.keyword} 的推送内容"
            )
        elif task.task_type == 'dingtalk' and task.dingtalk_config:
            send_dingtalk_notification.delay(
                task_id=task.id,
                webhook_url=task.dingtalk_config.webhook_url,
                message=f"这是关于 {task.keyword.keyword} 的推送内容"
            )
        elif task.task_type == 'feishu' and task.feishu_config:
            send_feishu_notification.delay(
                task_id=task.id,
                app_id=task.feishu_config.app_id,
                app_secret=task.feishu_config.app_secret,
                message=f"这是关于 {task.keyword.keyword} 的推送内容"
            )
        
        return f"Push task {task_id} has been scheduled"
        
    except ObjectDoesNotExist:
        return "Task not found"
    except Exception as e:
        return f"Error scheduling task: {str(e)}"

@shared_task(bind=True)
def send_feishu_notification(self, task_id, app_id, app_secret, message):
    try:
        task = PushTask.objects.get(id=task_id)
        
        # 获取飞书访问令牌
        token_url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
        token_data = {
            "app_id": app_id,
            "app_secret": app_secret
        }
        
        token_response = requests.post(token_url, json=token_data)
        token_result = token_response.json()
        
        if token_result.get('code') != 0:
            PushHistory.objects.create(
                task=task,
                status='failed',
                result_message=f"获取飞书访问令牌失败: {token_result.get('msg', 'Unknown error')}"
            )
            return f"Failed to get Feishu token: {token_result.get('msg', 'Unknown error')}"
        
        access_token = token_result['tenant_access_token']
        
        # 发送飞书消息
        send_message_url = "https://open.feishu.cn/open-apis/message/v4/send"
        headers = {
            'Authorization': f'Bearer {access_token}',
            'Content-Type': 'application/json'
        }
        
        message_data = {
            "msg_type": "text",
            "content": {
                "text": message
            }
        }
        
        response = requests.post(send_message_url, headers=headers, json=message_data)
        result = response.json()
        
        if result.get('code') == 0:
            PushHistory.objects.create(
                task=task,
                status='success',
                result_message="飞书消息发送成功"
            )
            return "Feishu message sent successfully!"
        else:
            PushHistory.objects.create(
                task=task,
                status='failed',
                result_message=f"飞书消息发送失败: {result.get('msg', 'Unknown error')}"
            )
            return f"Feishu message failed: {result.get('msg', 'Unknown error')}"
        
    except ObjectDoesNotExist:
        return "Task not found"
    except Exception as e:
        PushHistory.objects.create(
            task=task,
            status='failed',
            result_message=f"飞书消息发送过程中发生错误: {str(e)}"
        )
        return f"Error occurred: {str(e)}"